#region Usings

using System;
using System.Configuration;
using System.Reflection;
using log4net;

#endregion

namespace Karma.Framework.Core.Configuration.Base
{
    public abstract class ConfigurationElementCollectionBase<T> : ConfigurationElementCollection
        where T : ConfigurationElement
    {
        private static readonly ILog LOG =
            LogManager.GetLogger(typeof (ConfigurationElementCollectionBase<T>).Name);

        #region Overrides

        protected override ConfigurationElement CreateNewElement()
        {
            return Activator.CreateInstance(typeof (T)) as ConfigurationElement;
        }

        #endregion

        #region Fields

        private static readonly ConfigurationPropertyCollection properties =
            new ConfigurationPropertyCollection();

        #endregion

        #region Properties

        protected override ConfigurationPropertyCollection Properties
        {
            get { return properties; }
        }

        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }

        protected override string ElementName
        {
            get
            {
                var target = typeof (T);
                var field = target.GetField(
                    "ELEMENT_NAME", BindingFlags.Static | BindingFlags.Public);
                return (string) field.GetValue(null);
            }
        }

        #endregion

        #region Indexers

        public T this[int index]
        {
            get { return (T) BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                base.BaseAdd(index, value);
            }
        }

        public new T this[string name]
        {
            get { return (T) BaseGet(name); }
        }

        #endregion
    }
}